/**
 * 
 */
package com.techq.weibo.robot.imp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.log4j.Logger;

import com.techq.weibo.auth.imp.SinaWeiboAuth;
import com.techq.weibo.meta.User;
import com.techq.weibo.robot.AbstractCrawlRobot;
import com.techq.weibo.share.enums.DestShare;
import com.techq.weibo.share.enums.Target;
import com.techq.weibo.share.exception.ShareException;

/**
 * @author tassemble@gmail.com 2011-8-2
 */
public class SinaWeiboCrawler extends AbstractCrawlRobot {

	/**
	 * 
	 */
	Logger logger = Logger.getLogger(SinaWeiboCrawler.class);
	
	
	public SinaWeiboCrawler() {
		
	}

	@Override
	public boolean auth(String url, User user) throws ShareException {
		return new SinaWeiboAuth().login(this, url, user);
	}

	@Override
	public String lookUp(Target target, String url, DestShare dest)
			throws ShareException {
		// for test

		if (target == Target.Youku && dest == DestShare.Sina) {
			String match = "http://v.t.sina.com.cn/share/share.php";
			
			StringBuilder content = this.get(url);
			
			//logger.debug(content.toString());
			
			int start = -1;
			int end = -1;
			if ((start = content.indexOf(match)) == -1) {
				throw new ShareException("url is not valid, can't find the share url");
			}
			if ((end = content.indexOf("\" target=\"_blank\">", start)) == -1) {
				throw new ShareException("url is not valid, can't find the share url");
			}
			
			String shareUrl = content.substring(start, end);
			
			logger.info("share url:" + shareUrl);
		
			return shareUrl;
		}
		
		throw new ShareException("no such target and dest");
	}

	@Override
	public boolean hasAuthed() {
		// TODO Auto-generated method stub
		return false;
	}
	
	

}
